package com.sojson.util.search.es.util;

import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

/**
 * ES查询工具类
 * 
 * @author liu
 * @date 2022-07-25
 */
public class EsSearchUtil {

    /** 查询对象 */
    private BoolQueryBuilder query;

    public EsSearchUtil(BoolQueryBuilder query) {
        this.query = query;
    }

    /**
     * 并且
     * 
     * @param builder   查询条件{@link #createQuery()}
     * @return
     */
    public BoolQueryBuilder and(AbstractQueryBuilder<?> builder) {
        query = query.must(builder);
        return query;
    }

    /**
     * 或者
     * 
     * @param builder   查询条件{@link #createQuery()}
     * @return
     */
    public BoolQueryBuilder or(AbstractQueryBuilder<?> builder) {
        query = query.should(builder);
        return query;
    }

    /**
     * 不等于
     * 
     * @param builder   查询条件{@link #createQuery()}
     * @return
     */
    public BoolQueryBuilder not(AbstractQueryBuilder<?> builder) {
        query = query.mustNot(builder);
        return query;
    }

    /**
     * 创建嵌套对象</BR>
     * 属性的类型必须是nested</BR>
     * 因为es7以后把type概念去掉了,所以类型只能通过json文件建立</BR>
     * 子对象的字段名必须是{父字段名.子字段名}</BR>
     * 
     * @param proName   对象名称
     * @param builder   查询条件{@link #createQuery()}
     * @return
     */
    public AbstractQueryBuilder<?> createNested(String proName, AbstractQueryBuilder<?> builder) {
        return QueryBuilders.nestedQuery(proName, builder, ScoreMode.None);
    }

    /**
     * 创建查询条件
     * 
     * @return
     * @throws Exception
     */
    public EsQueryBuilderUtil createQuery() throws Exception {
        return new EsQueryBuilderUtil();
    }

    /**
     * 创建子查询条件
     * 
     * @param parentFieldName   父类字段名
     * @return
     * @throws Exception
     */
    public EsQueryBuilderUtil createQuery(String parentFieldName) throws Exception {
        return new EsQueryBuilderUtil(parentFieldName);
    }

    /**
     * 创建脚本字段
     * 
     * @return
     * @throws Exception
     */
    public EsScriptUtil createScript() throws Exception {
        return new EsScriptUtil();
    }

    /**
     * 构建查询对象
     * 
     * @return
     */
    public BoolQueryBuilder build() {
        return query;
    }

}